/*
 * MunicipiosAgregarFrame.java
 *
 * Created on 27 de abril de 2008, 11:50 AM
 */
package org.contabilidad.municipios;

import org.mybeans.Sesion;
import org.mybeans.MunicipiosBeans;
 
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

/**
 *
 * @author  avbravo
 */
public class MunicipiosAgregarFrame extends javax.swing.JFrame {

    Sesion sesion;
    MunicipiosBeans municipiosBeans;

    /** Creates new form MunicipiosAgregarFrame */
    public MunicipiosAgregarFrame() {
        initComponents();
         /*
             * Fondo
             */

            
              
             

             
             

            /*
             * fin del fondo
             */
        sesion = new Sesion();
        municipiosBeans = new MunicipiosBeans();
        CargarProvincias();
        AutoCompleteDecorator.decorate(this.jComboBoxProvincia);
        NuevoNumeroMunicipio();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldIdMunicipio = new javax.swing.JTextField();
        jTextFieldMunicipio = new javax.swing.JTextField();
        jComboBoxProvincia = new javax.swing.JComboBox();
        jButtonGuardar = new javax.swing.JButton();
        jButtonLimpiar = new javax.swing.JButton();
        jButtonRegresar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Agregar Municipios");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Codigo");

        jLabel2.setText("Municipio");

        jLabel3.setText("Provincia");

        jTextFieldIdMunicipio.setEditable(false);
        jTextFieldIdMunicipio.setEnabled(false);

        jComboBoxProvincia.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxProvinciaActionPerformed(evt);
            }
        });

        jButtonGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/save.png"))); // NOI18N
        jButtonGuardar.setToolTipText("Guardar");
        jButtonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGuardarActionPerformed(evt);
            }
        });

        jButtonLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/escoba.png"))); // NOI18N
        jButtonLimpiar.setToolTipText("Limpiar");
        jButtonLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLimpiarActionPerformed(evt);
            }
        });

        jButtonRegresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/regresar.jpeg"))); // NOI18N
        jButtonRegresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRegresarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(42, 42, 42)
                        .addComponent(jButtonGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(26, 26, 26)
                        .addComponent(jButtonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(31, 31, 31)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextFieldMunicipio, javax.swing.GroupLayout.DEFAULT_SIZE, 314, Short.MAX_VALUE)
                            .addComponent(jTextFieldIdMunicipio, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jComboBoxProvincia, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(178, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jComboBoxProvincia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(16, 16, 16)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldIdMunicipio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldMunicipio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(37, 37, 37)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButtonRegresar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(2, 2, 2))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButtonGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButtonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(41, 41, 41))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButtonRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRegresarActionPerformed
 
    dispose();
}//GEN-LAST:event_jButtonRegresarActionPerformed

private void jButtonLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLimpiarActionPerformed
 
    jTextFieldIdMunicipio.setText("");
    jTextFieldMunicipio.setText("");
    NuevoNumeroMunicipio();
}//GEN-LAST:event_jButtonLimpiarActionPerformed

private void jButtonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarActionPerformed
 
    try {

        String idMunicipio = this.jTextFieldIdMunicipio.getText();
        if (idMunicipio == null || idMunicipio.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese el codigo del municipio", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldIdMunicipio.requestFocus();
            return;
        }

        String Municipio = this.jTextFieldMunicipio.getText();
        if (Municipio == null || Municipio.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese el municipio", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldMunicipio.requestFocus();
            return;
        }

        String Provincia = (String) this.jComboBoxProvincia.getSelectedItem();
        if (Provincia == null || Provincia.equals("")) {
            JOptionPane.showMessageDialog(this, "seleccione la provincia ", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        String IdProvincia = BuscarProvincias(Provincia);

        if (sesion.Conectar() == false) {
            JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        String sqlquery = "select * from municipies where idmunicipio = ?";
        PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
        psquery.setString(1, idMunicipio);
        ResultSet rs = psquery.executeQuery();
        rs.next();
        int x = rs.getRow();

        if (x != 0) {
            JOptionPane.showMessageDialog(this, "Existe un municipio con ese codigo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        String sql = "INSERT into municipies VALUES(?,?,?)";
        PreparedStatement prest = sesion.con.prepareStatement(sql);

        prest.setString(1, idMunicipio);
        prest.setString(2, Municipio);
        prest.setString(3, IdProvincia);

        int count = prest.executeUpdate();
        sesion.con.close();
        JOptionPane.showMessageDialog(this, "Municipio Guardado exitosamente", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
        municipiosBeans.setIdMunicipo(idMunicipio);
        municipiosBeans.setMunicipio(Municipio);
        municipiosBeans.setIdProvincia(IdProvincia);

        jTextFieldIdMunicipio.setText("");
    jTextFieldMunicipio.setText("");
    NuevoNumeroMunicipio();
    } catch (Exception ex) {
        System.out.println("Error" + ex);
        JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }

}//GEN-LAST:event_jButtonGuardarActionPerformed

private void jComboBoxProvinciaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxProvinciaActionPerformed
 
}//GEN-LAST:event_jComboBoxProvinciaActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MunicipiosAgregarFrame().setVisible(true);
            }
        });
    }

    private String BuscarProvincias(String Provincia) {
        try {
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return "";
            }

            String sqlquery = "select * from provinces where provincia = ? ";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            psquery.setString(1, Provincia);

            ResultSet rs = psquery.executeQuery();
            rs.next();
            int x = rs.getRow();

            if (x == 0) {
                JOptionPane.showMessageDialog(this, "no existe una provincia con ese nombre", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return "";
            }
            return rs.getString("idprovincia");


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        return "";
    }

    private void CargarProvincias() {
        try {
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            String sqlquery = "select idprovincia, provincia from provinces order by provincia";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            ResultSet rs = psquery.executeQuery();
            jComboBoxProvincia.removeAllItems();
            int count = 0;
            while (rs.next()) {
                String provincia = rs.getString("provincia");
                jComboBoxProvincia.insertItemAt(provincia, count);
                count++;
            }
            if (count != 0) {
                jComboBoxProvincia.setSelectedIndex(0);
            }


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error Cargando Corregimientos" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

      private void NuevoNumeroMunicipio() {
        try {
            //   int NuevoNumeroRecibo = recibesBeans.getNumeroReciboDisponible();
            int NuevoNumero = municipiosBeans.MunicipioUltimo();
            if (NuevoNumero != -1) {
                NuevoNumero++;
                jTextFieldIdMunicipio.setText(String.valueOf(NuevoNumero));

            } else {
                sesion.MostrarMensajeInformacion("Mensaje", "No se genero ningun numero municipio");
            }
        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "CrearNuevoRecibo()\n " + ex.getMessage().toString());
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonGuardar;
    private javax.swing.JButton jButtonLimpiar;
    private javax.swing.JButton jButtonRegresar;
    private javax.swing.JComboBox jComboBoxProvincia;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTextFieldIdMunicipio;
    private javax.swing.JTextField jTextFieldMunicipio;
    // End of variables declaration//GEN-END:variables
}
